package ajax;

import helpers.EmailHelper;
import helpers.StringHelper;
import helpers.UrlHelper;

import java.io.IOException;
import java.util.Date;
import java.util.logging.Level;
import java.util.logging.Logger;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import admin.controllers.SendDealEmailServlet;

import systems.ConfigSystem;

import models.SiteConfigModel;
import models.UserModel;

import data.UserData;
import debugs.UserDebug;

public class EmailForgetPassAjaxServlet extends HttpServlet{
	
	private static final Logger log = Logger.getLogger(EmailForgetPassAjaxServlet.class.getName());
	
	public void doGet(HttpServletRequest request, HttpServletResponse response)
		throws IOException, ServletException {		
		log.setLevel(Level.FINE);

		SiteConfigModel configs = ConfigSystem.getConfigs();
		
		String email = (String) request.getParameter("email");
		
		UserData userData = new UserData();
		UserModel user = userData.getUser(email);
		
		if (user != null) {
			String codeReset = StringHelper.md5(Long.toString(System.nanoTime()));
			
			//update code reset and date expired
			user.setCodeReset(codeReset);
			user.setExpired(new Date());
			userData.insert(user);
			
			String subject = "Quên mật khẩu đăng nhập onsale365.com.vn";
			/*String body = UrlHelper.getServerUrl(request) + "/reset-password?key=" + codeReset;
			response.getWriter().println(body);
			String fromEmail = "hoantocxoan@gmail.com";
			
			//Send mail
			EmailHelper.sendMail(subject, body, fromEmail, email);*/
			
			String url = UrlHelper.getServerUrl(request) + "/preview-email-forget-password?email=" + email;
			SendDealEmailServlet.sendData("onsale365 <info@onsale365.com.vn>", subject, url, email);
			System.out.println(url);
			
			
			
			log.info("Sended mail to reset password for email : " + email);
		} else {
			log.warning("Not exists user :" + email);
		}
	}
}
